package com.hcloud.auth.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hcloud.auth.audit.LoginLogService;
import com.hcloud.common.core.base.HCloudResult;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证失败时封装消息返回
 *
 * @author hepangui
 * @Date 2018-12-12
 */
@Component("hcloudAuthenticationFailureHandler")
@Slf4j
@AllArgsConstructor
public class HcloudAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {


    private final ObjectMapper objectMapper;

    private final LoginLogService loginLogService;

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                        AuthenticationException e) throws IOException, ServletException {
        log.info("登录失败");
        httpServletResponse.setStatus(HttpStatus.OK.value());
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        //将authentication这个对象转成json格式的字符串
        String msg = e.getMessage();
        if(e instanceof InternalAuthenticationServiceException
            || e instanceof BadCredentialsException){
            msg = "用户名或密码错误";
        }
        loginLogService.saveErrorLog(null,msg);
        httpServletResponse.getWriter().write(objectMapper.writeValueAsString(new HCloudResult<>(msg)));

    }
}
